//
//  CHCalendarView.m
//  CarFile
//
//  Created by 陈浩 on 2017/8/9.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHCalendarView.h"

@implementation CHCalendarView

{
    UIButton  *_selectButton;
    
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
       self.backgroundColor = [UIColor whiteColor]; 
        
    }
    return self;
}





#pragma mark - date

- (NSInteger)day:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components day];
}


- (NSInteger)month:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components month];
}

- (NSInteger)year:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components year];
}


- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}

- (NSInteger)totaldaysInMonth:(NSDate *)date{
    NSRange daysInOfMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return daysInOfMonth.length;
}

- (NSDate *)lastMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = -1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

- (NSDate*)nextMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = +1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

#pragma mark - create View

-(void)setDateArr:(NSArray *)dateArr{
    _dateArr = dateArr;
    
    [self createCalendarViewWith:[self turnDateWithDateStr:dateArr[0]]];
    
}


- (void)createCalendarViewWith:(NSDate *)date{
    
    CGFloat itemW     = (UIScreenW +3) / 7;
    CGFloat itemH     = (400- 7*10 - 88-20) / 8;
    
    // 1.year month
    UILabel *headlabel = [[UILabel alloc] init];
    
    headlabel.text     = [NSString stringWithFormat:@"   %li月",[self month:date]];
    headlabel.font     = [UIFont systemFontOfSize:20];
    headlabel.textColor = [UIColor colorWithHexString:@"999999" alpha:1.0f];
    headlabel.frame           = CGRectMake(0, 0, UIScreenW, 44);
    headlabel.textAlignment   = NSTextAlignmentLeft;
    [self addSubview:headlabel];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 44, UIScreenW, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"999999" alpha:0.1];
    [self addSubview:line];
    
    // 2.weekday
    NSArray *array = @[@"日", @"一", @"二", @"三", @"四", @"五", @"六"];
    UIView *weekBg = [[UIView alloc] init];
    weekBg.frame = CGRectMake(0, CGRectGetMaxY(headlabel.frame), UIScreenW, 44);
    [self addSubview:weekBg];
    
    for (int i = 0; i < 7; i++) {
        
        UILabel *week = [[UILabel alloc] init];
        week.text     = array[i];
        week.font     = [UIFont systemFontOfSize:18];
        week.frame    = CGRectMake(itemW * i, 0, itemW, 44);
        week.textAlignment   = NSTextAlignmentCenter;
        week.backgroundColor = [UIColor clearColor];
        week.textColor       = [UIColor blackColor];
        [weekBg addSubview:week];
    }
    
    //  3.days (1-31)
    for (int i = 0; i < 42; i++) {
        
        int x = (i % 7) * itemW ;
        int y = (i / 7) * (itemH+20) + CGRectGetMaxY(weekBg.frame)+20;
        UIButton *dayButton = [[UIButton alloc] init];
        dayButton.frame = CGRectMake(x, y, itemW, itemH);
        dayButton.titleLabel.font = [UIFont systemFontOfSize:16.0];
        dayButton.titleLabel.textAlignment = NSTextAlignmentCenter;
      
        NSInteger daysInLastMonth = [self totaldaysInMonth:[self lastMonth:date]];
        NSInteger daysInThisMonth = [self totaldaysInMonth:date];
        NSInteger firstWeekday    = [self firstWeekdayInThisMonth:date];
        
        NSInteger day = 0;
        
        
        if (i < firstWeekday) {
            day = daysInLastMonth - firstWeekday + i + 1;
            [self setStyle_BeyondThisMonth:dayButton];
            
        }else if (i > firstWeekday + daysInThisMonth - 1){
            day = i + 1 - firstWeekday - daysInThisMonth;
            [self setStyle_BeyondThisMonth:dayButton];
            
        }else{
            day = i - firstWeekday + 1;
            [self setStyle_AfterToday:dayButton];
        }
        
        [dayButton setTitle:[NSString stringWithFormat:@"%li", day] forState:UIControlStateNormal];
        [self addSubview:dayButton];
        
        
        for (int j = 0; j< self.dateArr.count; j++) {
            
            
            
            NSDate *dayDate = [self turnDateWithDateStr:self.dateArr[j]];
            
            if ([self month:dayDate] == [self month:date]) {
                
                NSInteger todayIndex = [self day:dayDate] + firstWeekday - 1;
                
                if (i < todayIndex && i >= firstWeekday) {
                    //                            [self setStyle_BeforeToday:dayButton];
                    
                }else if(i ==  todayIndex){
                    [self setStyle_Today:dayButton];
                    
                }
            }
            
        }
        
    }
}


-(NSDate *)turnDateWithDateStr:(NSString *)dateStr{
    

    
    // 日期格式化类
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    
    // 设置日期格式 为了转换成功
    
    format.dateFormat =  @"yyyy-MM-dd";
    //  [format setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *date = [format dateFromString:dateStr];
    
    return date;
    
}



#pragma mark - date button style

- (void)setStyle_BeyondThisMonth:(UIButton *)btn
{
    btn.hidden = YES;
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
}

- (void)setStyle_BeforeToday:(UIButton *)btn
{
    btn.hidden = YES;
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
}

- (void)setStyle_Today:(UIButton *)btn
{
    btn.hidden = NO;
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [btn setBackgroundColor:KRGB(167, 192, 247)];
}

- (void)setStyle_AfterToday:(UIButton *)btn
{
    btn.hidden = NO;
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}



@end
